<script setup>
import {
    Edit, Delete, Position, Upload
} from '@element-plus/icons-vue'
import {

} from '@/api/allApi.js'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    getallbookservice, getpartpathservice,
    updatepathservice, detailbookservice, deletepathservice, lendbookservice, getallbookcategoryservice
} from '@/api/book.js'
import { getpartf3service, deletef3service } from '@/api/allApi.js'
import {
    addclientcomeservice, getpartclientservice,
    getAllUserForClientComeAddservice, updateclientcomeservice
} from '@/api/client.js'
//控制添加分类弹窗
const dialogVisible = ref(false)
const lenddialogVisible = ref(false)
//分页条数据模型
//const pageNum = ref(1)//当前页
const total = ref(20)//总条数
//const pageSize = ref(3)//每页条数
//文章分类数据模型
const clients = ref([])
const users = ref([])
const userdepartment = ref(null)
//用户搜索时选中的分类id
const bookcategorylist = async () => {
    let result = await getpartclientservice({
        pageNum: 1,
        pageSize: 1000,
        str: ''
    });
    clients.value = result.data.items;
    console.log(clients.value);

}
bookcategorylist();
const listuser = async () => {
    let result = await getAllUserForClientComeAddservice();

    users.value = result.data;
    console.log(result);
}
listuser();
//定义变量，控制标题
const title = ref('')
//与后端交互的json数据
const pathmodel = ref({
    id: null,
    clientcompanyid: null,
    status: null,
    comedate: null,
    userid: null,
    department: null,
    whycome: null,
    comment: null
})
const sheets = ref([{}, {}])

const findmodel = ref({
    pageNum: 1,
    pageSize: 5,
    str: ''
})
const f3list = async () => {
    console.log(findmodel.value);
    let result = await getpartf3service(findmodel.value);
    console.log(result);
    total.value = result.data.total;
    sheets.value = result.data.items;
}
f3list();
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    findmodel.value.pageSize = size;
    f3list();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    findmodel.value.pageNum = num;
    f3list();
}
const cleardata = () => {
    findmodel.value.str = ''
}
//表单校验
const rules = {
    clientcompanyid: [
        { required: true, message: '请选择客户', trigger: 'blur' },
    ],
    status: [
        { required: true, message: '请输入状态', trigger: 'blur' },
    ],
    comedate: [
        { required: true, message: '请选择日期', trigger: 'blur' },
    ],
    userid: [
        { required: true, message: '请选择联络员', trigger: 'blur' },
    ],
    whycome: [
        { required: true, message: '请输入来访事宜', trigger: 'blur' },
    ],
    comment: [
        { required: true, message: '请输入备注', trigger: 'blur' },
    ],
    xx: [
        { required: false, message: '', trigger: 'blur' },
    ]
}
const add = () => {
    for (let key in pathmodel.value) {
        if (pathmodel.value.hasOwnProperty(key)) {
            pathmodel.value[key] = null;
        }
    }
    userdepartment.value = null
    dialogVisible.value = true;
    title.value = '添加客户来访信息'
}
const formref = ref(null); //表单校验
const addpath = async () => {
    console.log(pathmodel.value);
    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            console.log(pathmodel.value);
            let result = await addclientcomeservice(pathmodel.value);
            if (result.code == 0) {
                ElMessage.success("添加成功")
                dialogVisible.value = false;
                f3list();
            }
            else {
                ElMessage.error(result.message ? result.message : '添加失败')
            }
        }
    });
}
const updatepath = async () => {
    console.log(pathmodel.value);
    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            console.log(pathmodel.value);
            let result = await updateclientcomeservice(pathmodel.value);
            if (result.code == 0) {
                ElMessage.success("修改成功")
                dialogVisible.value = false;
                f3list();
            }
            else {
                ElMessage.error(result.message ? result.message : '修改失败')
            }
        }
    });
}
//删除分类
const del = (row) => {
    ElMessageBox.confirm(
        '你确认删除该条信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //用户点击了确认
            let result = await deletef3service(row.id)
            if (result.code == 0) {
                ElMessage.success('删除成功')
                f3list();
            }
            else {
                ElMessage.error('删除失败')
            }
        })
        .catch(() => {
            //用户点击了取消
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
//展示编辑弹窗
const showDialog = (row) => {
    title.value = '编辑来访信息';
    dialogVisible.value = true;
    //数据拷贝
    Object.keys(row).forEach((key) => {
        pathmodel.value[key] = row[key];
    });
    console.log(row);

    const user = users.value.find(user => user.id === row.userid);
    userdepartment.value = user.department
    pathmodel.value.department = user.department
}

const handleUserChange = (id) => {
    console.log(id);
    const user = users.value.find(user => user.id === id) ? users.value.find(user => user.id === id) : null;
    if (user != null) {
        userdepartment.value = user.department
        pathmodel.value.department = user.department
        console.log(userdepartment.value);
    } else {
        userdepartment.value = null
        pathmodel.value.department = null
    }


}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>客户来访</span>
                <div class="extra">
                    <el-button type="primary" @click="add">添加来访</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="查询条件：">
                <el-input v-model="findmodel.str" placeholder="请输入查询内容" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="f3list">搜索</el-button>
                <el-button @click="cleardata">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 文章列表 -->
        <el-table :data="sheets" style="width: 100%">
            <el-table-column label="序号" width="60" type="index"> </el-table-column>
            <el-table-column label="客户序号" prop="clientcompanyid"> </el-table-column>
            <el-table-column label="客户名称" prop="clientname"> </el-table-column>
            <el-table-column label="状态" prop="status"> </el-table-column>
            <el-table-column label="日期" prop="comedate"></el-table-column>
            <el-table-column label="备注" prop="comment"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="del(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="findmodel.pageNum" v-model:page-size="findmodel.pageSize"
            :page-sizes="[5, 10, 15, 20]" layout="jumper, total, sizes, prev, pager, next" background :total="total"
            @size-change="onSizeChange" @current-change="onCurrentChange"
            style="margin-top: 20px; justify-content: flex-end" />
    </el-card>
    <!-- 添加分类弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="40%">
        <el-form :model="pathmodel" ref="formref" :rules="rules" label-width="125px" style="padding-right: 30px">
            <el-row gutter="20">
                <el-col :span="24">
                    <el-form-item label="客户名称" prop="clientcompanyid">
                        <el-select placeholder="请选择客户" clearable style="width: 500px"
                            v-model="pathmodel.clientcompanyid">
                            <el-option v-for="c in clients" :key="c.id" :label="c.clientcompanyname" :value="c.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row gutter="20">
                <el-col :span="12">
                    <el-form-item label="状态" prop="status">
                        <el-input v-model="pathmodel.status"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="日期" prop="comedate">
                        <el-date-picker v-model="pathmodel.comedate" style="width: 350px" type="date"
                            placeholder="请选择..." format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row gutter="20">
                <el-col :span="12">
                    <el-form-item label="联络员" prop="userid">
                        <el-select placeholder="请选择..." clearable style="width: 350px" v-model="pathmodel.userid"
                            @change="handleUserChange" @clear="clearselect">
                            <el-option v-for="c in users" :key="c.id" :label="c.name" :value="c.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联络员所属部门" prop="xx">
                        <el-input disabled v-model="userdepartment"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="来访事宜" prop="whycome">
                <el-input type="textarea" :rows="4" v-model="pathmodel.whycome" style="width: 500px"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="comment">
                <el-input type="textarea" :rows="4" v-model="pathmodel.comment" style="width: 500px"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="title == '添加客户来访信息' ? addpath() : updatepath()"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>

</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>